import * as vscode from 'vscode';
import axios from 'axios';

interface Recommendation {
    function_id: string;
    function_name: string;
    function_file: string;
    call_frequency?: number;
    recommendation_type: string;
    reason: string;
    query_source?: string;
}

interface ApiResponse {
    success: boolean;
    data: Recommendation[];
    count: number;
    error?: string;
}

class Neo4jRecommender {
    private apiUrl: string;
    private maxRecommendations: number;
    private showReason: boolean;

    constructor() {
        const config = vscode.workspace.getConfiguration('neo4jRecommender');
        this.apiUrl = config.get('apiUrl', 'http://localhost:5000');
        this.maxRecommendations = config.get('maxRecommendations', 10);
        this.showReason = config.get('showReason', true);
    }

    private async makeApiRequest(endpoint: string, data: any): Promise<ApiResponse> {
        try {
            const response = await axios.post(`${this.apiUrl}${endpoint}`, data, {
                timeout: 5000,
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            return response.data;
        } catch (error: any) {
            if (error.code === 'ECONNREFUSED') {
                throw new Error('无法连接到代码推荐API服务，请确保服务正在运行');
            }
            throw new Error(`API请求失败: ${error.message}`);
        }
    }

    async getFunctionRecommendations(functionName: string, contextFile?: string): Promise<Recommendation[]> {
        const response = await this.makeApiRequest('/recommendations/function', {
            function_name: functionName,
            context_file: contextFile,
            limit: this.maxRecommendations
        });

        if (!response.success) {
            throw new Error(response.error || '获取推荐失败');
        }

        return response.data;
    }

    async getNextFunctionCalls(functionName: string): Promise<Recommendation[]> {
        const response = await this.makeApiRequest('/recommendations/next-calls', {
            function_name: functionName,
            limit: this.maxRecommendations
        });

        if (!response.success) {
            throw new Error(response.error || '获取下一个调用失败');
        }

        return response.data;
    }

    async searchFunctions(query: string): Promise<Recommendation[]> {
        const response = await this.makeApiRequest('/search/functions', {
            query: query,
            limit: this.maxRecommendations
        });

        if (!response.success) {
            throw new Error(response.error || '搜索函数失败');
        }

        return response.data;
    }

    async getContextAwareRecommendations(currentFile: string, currentLine: number): Promise<Recommendation[]> {
        const response = await this.makeApiRequest('/recommendations/context', {
            current_file: currentFile,
            current_line: currentLine,
            limit: this.maxRecommendations
        });

        if (!response.success) {
            throw new Error(response.error || '获取上下文推荐失败');
        }

        return response.data;
    }

    async getPopularFunctions(filePattern?: string): Promise<Recommendation[]> {
        const response = await this.makeApiRequest('/recommendations/popular', {
            file_pattern: filePattern,
            limit: this.maxRecommendations
        });

        if (!response.success) {
            throw new Error(response.error || '获取受欢迎函数失败');
        }

        return response.data;
    }

    async getDatabaseStats(): Promise<any> {
        try {
            const response = await axios.get(`${this.apiUrl}/stats`, { timeout: 5000 });
            return response.data;
        } catch (error: any) {
            throw new Error(`获取统计信息失败: ${error.message}`);
        }
    }

    formatRecommendation(rec: Recommendation): string {
        let result = `📝 ${rec.function_name}`;
        
        if (rec.function_file) {
            result += ` (${rec.function_file})`;
        }
        
        if (this.showReason && rec.reason) {
            result += `\n   💡 ${rec.reason}`;
        }
        
        if (rec.call_frequency !== undefined) {
            result += `\n   📊 调用频率: ${rec.call_frequency}`;
        }
        
        return result;
    }
}

export function activate(context: vscode.ExtensionContext) {
    const recommender = new Neo4jRecommender();

    // 注册命令：获取函数推荐
    const getRecommendationsCommand = vscode.commands.registerCommand(
        'neo4j-recommender.getRecommendations',
        async () => {
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showWarningMessage('请先打开一个文件');
                return;
            }

            const selection = editor.selection;
            const selectedText = editor.document.getText(selection);
            
            if (!selectedText.trim()) {
                vscode.window.showWarningMessage('请先选择一个函数名');
                return;
            }

            try {
                vscode.window.withProgress({
                    location: vscode.ProgressLocation.Notification,
                    title: "获取代码推荐...",
                    cancellable: false
                }, async (progress) => {
                    const currentFile = editor.document.fileName;
                    const recommendations = await recommender.getFunctionRecommendations(
                        selectedText.trim(), 
                        currentFile
                    );

                    if (recommendations.length === 0) {
                        vscode.window.showInformationMessage('没有找到相关推荐');
                        return;
                    }

                    // 显示推荐列表
                    const items = recommendations.map(rec => ({
                        label: rec.function_name,
                        description: rec.function_file,
                        detail: recommender.formatRecommendation(rec),
                        rec: rec
                    }));

                    const selected = await vscode.window.showQuickPick(items, {
                        placeHolder: '选择要插入的推荐函数',
                        matchOnDescription: true,
                        matchOnDetail: true
                    });

                    if (selected) {
                        // 在光标位置插入函数名
                        await editor.edit(editBuilder => {
                            editBuilder.replace(selection, selected.rec.function_name);
                        });
                    }
                });
            } catch (error: any) {
                vscode.window.showErrorMessage(`获取推荐失败: ${error.message}`);
            }
        }
    );

    // 注册命令：获取下一个函数调用
    const getNextCallsCommand = vscode.commands.registerCommand(
        'neo4j-recommender.getNextCalls',
        async () => {
            const editor = vscode.window.activeTextEditor;
            if (!editor) {
                vscode.window.showWarningMessage('请先打开一个文件');
                return;
            }

            const selection = editor.selection;
            const selectedText = editor.document.getText(selection);
            
            if (!selectedText.trim()) {
                vscode.window.showWarningMessage('请先选择一个函数名');
                return;
            }

            try {
                vscode.window.withProgress({
                    location: vscode.ProgressLocation.Notification,
                    title: "获取下一个函数调用...",
                    cancellable: false
                }, async (progress) => {
                    const nextCalls = await recommender.getNextFunctionCalls(selectedText.trim());

                    if (nextCalls.length === 0) {
                        vscode.window.showInformationMessage('没有找到下一个调用建议');
                        return;
                    }

                    // 显示下一个调用列表
                    const items = nextCalls.map(rec => ({
                        label: rec.function_name,
                        description: rec.function_file,
                        detail: recommender.formatRecommendation(rec),
                        rec: rec
                    }));

                    const selected = await vscode.window.showQuickPick(items, {
                        placeHolder: '选择下一个要调用的函数',
                        matchOnDescription: true,
                        matchOnDetail: true
                    });

                    if (selected) {
                        // 在光标位置插入函数调用
                        const functionCall = `${selected.rec.function_name}();`;
                        await editor.edit(editBuilder => {
                            editBuilder.replace(selection, functionCall);
                        });
                    }
                });
            } catch (error: any) {
                vscode.window.showErrorMessage(`获取下一个调用失败: ${error.message}`);
            }
        }
    );

    // 注册命令：搜索函数
    const searchFunctionsCommand = vscode.commands.registerCommand(
        'neo4j-recommender.searchFunctions',
        async () => {
            const searchTerm = await vscode.window.showInputBox({
                prompt: '输入要搜索的函数名',
                placeHolder: '例如: process, main, init'
            });

            if (!searchTerm) {
                return;
            }

            try {
                vscode.window.withProgress({
                    location: vscode.ProgressLocation.Notification,
                    title: "搜索函数...",
                    cancellable: false
                }, async (progress) => {
                    const functions = await recommender.searchFunctions(searchTerm);

                    if (functions.length === 0) {
                        vscode.window.showInformationMessage(`没有找到包含 "${searchTerm}" 的函数`);
                        return;
                    }

                    // 显示搜索结果
                    const items = functions.map(rec => ({
                        label: rec.function_name,
                        description: rec.function_file,
                        detail: recommender.formatRecommendation(rec),
                        rec: rec
                    }));

                    const selected = await vscode.window.showQuickPick(items, {
                        placeHolder: `搜索结果: "${searchTerm}"`,
                        matchOnDescription: true,
                        matchOnDetail: true
                    });

                    if (selected) {
                        // 打开包含该函数的文件
                        const uri = vscode.Uri.file(selected.rec.function_file);
                        await vscode.window.showTextDocument(uri);
                    }
                });
            } catch (error: any) {
                vscode.window.showErrorMessage(`搜索失败: ${error.message}`);
            }
        }
    );

    // 注册命令：显示数据库统计
    const showStatsCommand = vscode.commands.registerCommand(
        'neo4j-recommender.showStats',
        async () => {
            try {
                vscode.window.withProgress({
                    location: vscode.ProgressLocation.Notification,
                    title: "获取数据库统计...",
                    cancellable: false
                }, async (progress) => {
                    const stats = await recommender.getDatabaseStats();

                    if (stats.success) {
                        const data = stats.data;
                        const message = `📊 数据库统计信息:\n\n` +
                            `📝 函数总数: ${data.function_count}\n` +
                            `🔗 调用关系总数: ${data.call_count}\n` +
                            `📁 文件总数: ${data.file_count}`;
                        
                        vscode.window.showInformationMessage(message);
                    } else {
                        vscode.window.showErrorMessage('获取统计信息失败');
                    }
                });
            } catch (error: any) {
                vscode.window.showErrorMessage(`获取统计信息失败: ${error.message}`);
            }
        }
    );

    // 注册自动补全提供者
    const completionProvider = vscode.languages.registerCompletionItemProvider(
        { scheme: 'file' },
        {
            async provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
                const config = vscode.workspace.getConfiguration('neo4jRecommender');
                const enableAutoComplete = config.get('enableAutoComplete', true);
                
                if (!enableAutoComplete) {
                    return [];
                }

                try {
                    const lineText = document.lineAt(position).text;
                    const currentFile = document.fileName;
                    const currentLine = position.line + 1;

                    // 获取上下文感知的推荐
                    const recommendations = await recommender.getContextAwareRecommendations(
                        currentFile, currentLine
                    );

                    return recommendations.map(rec => {
                        const item = new vscode.CompletionItem(
                            rec.function_name,
                            vscode.CompletionItemKind.Function
                        );
                        
                        item.detail = rec.function_file;
                        item.documentation = new vscode.MarkdownString(
                            `**${rec.function_name}**\n\n` +
                            `文件: ${rec.function_file}\n\n` +
                            `推荐理由: ${rec.reason}`
                        );
                        
                        if (rec.call_frequency !== undefined) {
                            item.sortText = `0${rec.call_frequency}`;
                        }
                        
                        return item;
                    });
                } catch (error) {
                    // 静默处理错误，不影响正常的代码补全
                    return [];
                }
            }
        },
        '.', '::', '(' // 触发字符
    );

    // 注册所有命令和提供者
    context.subscriptions.push(
        getRecommendationsCommand,
        getNextCallsCommand,
        searchFunctionsCommand,
        showStatsCommand,
        completionProvider
    );

    // 显示激活消息
    vscode.window.showInformationMessage('Neo4j Code Recommender 扩展已激活！');
}

export function deactivate() {
    // 清理资源
}
